package com.gsmr.realm;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.gsmr.entity.MemberShip;
import com.gsmr.entity.User;
import com.gsmr.service.MemberShipService;
import com.gsmr.service.UserService;

/**
 * 自定义Reaml
 * @author user
 *
 */
public class MyRealm extends AuthorizingRealm{

	@Resource
	private UserService userService;
	
	@Resource
	private MemberShipService memberShipService;
	
	/**
	 * 为当前登录用户授予角色和权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 验证当前登录的用户
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		String userId=(String) token.getPrincipal();
		String groupIdForAuth = (String) SecurityUtils.getSubject().getSession().getAttribute("groupIdForAuth");
		
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("userName", userId);
		//通过token获取密码
		char[] password = (char[]) token.getCredentials();
		
		map.put("password", String.valueOf(password));
		
		map.put("groupId", groupIdForAuth);
		MemberShip memberShip=memberShipService.login(map);
		User user = memberShip.getUser();
		SecurityUtils.getSubject().getSession().removeAttribute("groupIdForAuth");
		
		if (user == null) return null;
		
		SecurityUtils.getSubject().getSession().setAttribute("currentUser", user);
		AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getId(), user.getPassword(), "xxx");
		if(memberShip != null){
			SecurityUtils.getSubject().getSession().setAttribute("currentMemberShip", memberShip);
			//SecurityUtils.getSubject().getSession().setTimeout(8*60*60*1000);
			//设置的时间单位是:ms,为负数时表示永不超时
			SecurityUtils.getSubject().getSession().setTimeout(-2000l);
		}
		return authcInfo;
	}
}